package com.demo.flavor.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.demo.flavor.R;

public class UILabel extends View {
    public UILabel(Context context) {
        this(context, null);
    }

    public UILabel(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public UILabel(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.UILabel);
        text = t.getString(R.styleable.UILabel_text);
        int textColor = t.getColor(R.styleable.UILabel_textColor, 0);
        float textSize = t.getDimensionPixelSize(R.styleable.UILabel_textSize, 15);
        t.recycle();
        mPaint = new Paint();
        mPaint.setColor(textColor);
        mPaint.setTextSize(textSize);
        mTextBounds = new Rect();
        mPaint.setAntiAlias(true);
        mPaint.getTextBounds(text, 0, text.length(), mTextBounds);
        paddingV = getPaddingBottom() + getPaddingTop();
        paddingH = getPaddingLeft() + getPaddingRight();
    }

    private final Paint mPaint;
    private String text;
    private Rect mTextBounds;
    private int paddingV;
    private int paddingH;

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(text, getPaddingLeft(), getPaddingTop() + mTextBounds.height(), mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        setMeasuredDimension(getMeasuredWidth(widthMeasureSpec), getMeasuredHeight(heightMeasureSpec));
    }

    private int getMeasuredWidth(int measureSpec) {
        int mode = MeasureSpec.getMode(measureSpec);
        int measuredSize = MeasureSpec.getSize(measureSpec) + paddingH;
        if (mode == MeasureSpec.EXACTLY) {
            // 指定特定的尺寸了,直接返回计算出的尺寸
            return measuredSize;
        }
        System.out.println(Math.min(mTextBounds.width() + paddingH, measuredSize));
        System.out.println(measuredSize);

        return mTextBounds.width() + paddingH;
    }

    private int getMeasuredHeight(int measureSpec) {
        int mode = MeasureSpec.getMode(measureSpec);
        int measuredSize = MeasureSpec.getSize(measureSpec) + paddingV;
        if (mode == MeasureSpec.EXACTLY) {
            // 指定特定的尺寸了,直接返回计算出的尺寸
            return measuredSize;
        }

        return mTextBounds.height() + paddingV;
    }
}
